package com.quicks.beauty.server.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.quicks.beauty.core.dao.BeautyProductMapper;
import com.quicks.beauty.core.dao.CustomMapper;
import com.quicks.beauty.core.dao.UserAccountDetailMapper;
import com.quicks.beauty.core.dao.UserAddressMapper;
import com.quicks.beauty.core.dao.UserOrderMapper;
import com.quicks.beauty.core.dao.UserPointAccountMapper;
import com.quicks.beauty.core.entity.BeautyProduct;
import com.quicks.beauty.core.entity.UserAccountDetail;
import com.quicks.beauty.core.entity.UserInvite;
import com.quicks.beauty.core.entity.UserOrder;
import com.quicks.beauty.core.entity.UserPointAccount;
import com.quicks.beauty.core.entity.UserPointAccountExample;
import com.quicks.beauty.core.utils.CommonUtils;
import com.quicks.beauty.core.utils.UUIDGenerator;
import com.quicks.beauty.core.vo.InviteUserVO;
import com.quicks.beauty.core.vo.ProductSub;
import com.quicks.beauty.core.vo.UserOrderDetailVO;
import com.quicks.beauty.core.vo.UserOrderVO;
import com.quicks.beauty.server.vos.GiftVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private UserOrderMapper orderMapper;

    @Autowired
    private BeautyProductMapper productMapper;

    @Autowired
    private UserPointAccountMapper pointAccountMapper;

    @Autowired
    private UserAccountDetailMapper accountDetailMapper;
    @Autowired
    private CustomMapper customMapper;
    @Autowired
    private RedisBillService redisBillService;


    @Transactional
    public int addUserOrder(GiftVO gift) throws Exception {
        int type = 0;
        int kinds = gift.getKinds();
        BeautyProduct product = productMapper.selectByPrimaryKey(gift.getProductId());
        Integer points = product.getPoints();
        List<UserPointAccount> pointAccounts = pointAccountMapper.selectByExample(gift.getUserId());
        UserPointAccount userPointAccount = pointAccounts.get(0);

        int num = gift.getNum();
        Date now = new Date();
        UserOrder order = new UserOrder();
        order.setId(UUIDGenerator.generate()).setProdId(gift.getProductId())
                .setUnitPoints(points).setNumber(num).setCreateTime(now).setMobile(gift.getMobile())
                .setUpdateTime(now).setKinds(kinds).setDeleted(0);
        order.setOrderCodes(CommonUtils.generateOrderNo("AP")).setUserId(gift.getUserId());
        if (kinds == 0) {
            Integer kinds2 = product.getKinds();
            if (kinds2 == 0) {
                order.setStates(4);
            } else {
                order.setStates(2);
            }
            Integer oldPoints = userPointAccount.getPoints();
            int end = oldPoints -points;
            if(end<0){
                return -1;
            }
            order.setCreateBy(gift.getUsername());
            order.setAppointTime(new Date(gift.getAppointTime())).setPoints(points * num).setAppointTimeEnd(new Date(gift.getAppointTimeEnd()));
            userPointAccount.setPoints(oldPoints - order.getPoints());
            UserAccountDetail accountDetail = new UserAccountDetail();
            accountDetail.setAccountId(userPointAccount.getId()).setCreateTime(now).setUserId(gift.getUserId())
                    .setPoints(-order.getPoints()).setId(UUIDGenerator.generate()).setStates(0);
            accountDetail.setKinds(0).setRemark("兑换" + product.getProdName() + num + "");
            int o1 = orderMapper.insert(order);
            int o2 = pointAccountMapper.updateByPrimaryKeySelective(userPointAccount);
            int o3 = accountDetailMapper.insert(accountDetail);
            type = o1 + o2 + o3;

        } else {
            order.setStates(0).setExpressFee(150).setPoints(points * num + 150);
            String addressId = gift.getAddressId();
            Integer oldPoints = userPointAccount.getPoints();
            int end = oldPoints - points;
            if(end<0){
                return -1;
            }
            userPointAccount.setPoints(oldPoints - order.getPoints());
            order.setAddressId(addressId);

            UserAccountDetail accountDetail = new UserAccountDetail();
            accountDetail.setAccountId(userPointAccount.getId()).setCreateTime(now).setUserId(gift.getUserId())
                    .setPoints(-order.getPoints()).setId(UUIDGenerator.generate()).setStates(0);
            accountDetail.setKinds(0).setRemark("兑换" + product.getProdName() + num + "");

            int m2 = orderMapper.insert(order);
            int m4 = accountDetailMapper.insert(accountDetail);
            int m3 = pointAccountMapper.updateByPrimaryKeySelective(userPointAccount);
            type = type + m2 + m3 + m4;
        }
//        type = 1;
        return type;
    }


    public int addOrderTwo(GiftVO gift){
        int type = 0;
        if(Integer.parseInt(gift.getTradeType())==0){

            int kinds = gift.getKinds();
            BeautyProduct product = productMapper.selectByPrimaryKey(gift.getProductId());
            Integer points = product.getPoints();
            List<UserPointAccount> pointAccounts = pointAccountMapper.selectByExample(gift.getUserId());
            UserPointAccount userPointAccount = pointAccounts.get(0);
            int userP = userPointAccount.getPoints();
            int num = gift.getNum();
            Date now = new Date();
            UserOrder order = new UserOrder();
            order.setId(UUIDGenerator.generate()).setProdId(gift.getProductId())
                    .setUnitPoints(points).setNumber(num).setCreateTime(now).setMobile(gift.getMobile())
                    .setUpdateTime(now).setKinds(kinds).setDeleted(0);
            order.setOrderCodes(CommonUtils.generateOrderNo("GP")).setUserId(gift.getUserId());
            order.setTradeType(0).setMoney(new BigDecimal(0));

            ProductSub ps = null;
            if (kinds == 0) {
                Integer kinds2 = product.getKinds();
                if (kinds2 == 0) {
                    order.setStates(4);
                    order.setTradeState(11);
                } else if(kinds2==2){
                    String subId = gift.getSubId();
                    ps = customMapper.findSubDetail(subId);
                    order.setSubsId(subId);
                    order.setKinds(1);
                    order.setStates(2);
                    order.setTradeState(12);
               /* DecimalFormat df = new DecimalFormat("#");
                BigDecimal re = ps.getPrice().multiply(BigDecimal.TEN);*/
                    order.setUnitPoints(ps.getPrice().multiply(BigDecimal.TEN).intValue());
                }else {
                    order.setKinds(1);
                    order.setStates(2);
                    order.setTradeState(12);
                }
                Integer oldPoints = userPointAccount.getPoints();
                order.setCreateBy(gift.getUsername());
                if(kinds2 ==2){
                    order.setPoints((ps.getPrice().multiply(new BigDecimal(num*10))).intValue());
                }else{
                    order.setPoints(points * num);
                }

                userPointAccount.setPoints(oldPoints - order.getPoints());
                UserAccountDetail accountDetail = new UserAccountDetail();
                accountDetail.setAccountId(userPointAccount.getId()).setCreateTime(now).setUserId(gift.getUserId())
                        .setPoints(-order.getPoints()).setId(UUIDGenerator.generate()).setStates(0);
                accountDetail.setSurplusPoints(oldPoints -order.getPoints() );
                accountDetail.setOrderId(order.getId());
                accountDetail.setKinds(0).setRemark("兑换" + product.getProdName() + num + "");
                int o1 = orderMapper.insert(order);
                int o2 = pointAccountMapper.updateByPrimaryKeySelective(userPointAccount);
                int o3 = accountDetailMapper.insert(accountDetail);
                type = o1 + o2 + o3;

            } else {
                if("1".equals(gift.getFangshi())){
                    order.setExpressCompany("顺丰速运");
                }else if("2".equals(gift.getFangshi())){
                    order.setExpressCompany("闪送");
                }
                Integer kinds1 = product.getKinds();

                if(kinds1 ==1){
                    if("1".equals(gift.getFangshi())){
                        order.setStates(0).setExpressFee(150).setPoints((points * num)+150);
                    }else if("2".equals(gift.getFangshi())){
                        order.setStates(0).setExpressFee(150).setPoints((points * num)+350);
                    }else {
                        order.setStates(0).setExpressFee(150).setPoints((points * num));
                    }

                }
                order.setTradeState(1);
                String addressId = gift.getAddressId();
                Integer oldPoints = userPointAccount.getPoints();



                if(kinds1==2){
                    String subId = gift.getSubId();
                    ps = customMapper.findSubDetail(subId);
                    if("1".equals(gift.getFangshi())){
                        order.setStates(0).setExpressFee(150).setPoints((ps.getPrice().multiply(new BigDecimal(num*10)).add(new BigDecimal(150))).intValue());
                    }else if("2".equals(gift.getFangshi())){
                        order.setStates(0).setExpressFee(150).setPoints((ps.getPrice().multiply(new BigDecimal(num*10)).add(new BigDecimal(350))).intValue());
                    }else {
                        order.setStates(0).setExpressFee(150).setPoints((ps.getPrice().multiply(new BigDecimal(num*10)).add(new BigDecimal(0))).intValue());
                    }


                    order.setSubsId(subId);
                    order.setKinds(1);
                    order.setUnitPoints(ps.getPrice().multiply(BigDecimal.TEN).intValue());
                }

                userPointAccount.setPoints(oldPoints - order.getPoints());
                order.setAddressId(addressId);

                UserAccountDetail accountDetail = new UserAccountDetail();
                accountDetail.setAccountId(userPointAccount.getId()).setCreateTime(now).setUserId(gift.getUserId())
                        .setPoints(-order.getPoints()).setId(UUIDGenerator.generate()).setStates(0);
                accountDetail.setSurplusPoints(oldPoints - order.getPoints());
                accountDetail.setOrderId(order.getId());
                accountDetail.setKinds(0).setRemark("兑换" + product.getProdName() + num + "");

                int m2 = orderMapper.insert(order);
                int m4 = accountDetailMapper.insert(accountDetail);
                int m3 = pointAccountMapper.updateByPrimaryKeySelective(userPointAccount);
                type = type + m2 + m3 + m4;
            }
//        type = 1;
            redisBillService.pushUserOrderById(gift.getUserId(), order.getId());
            return type;
        }else{
            int kinds = gift.getKinds();
            BeautyProduct product = productMapper.selectByPrimaryKey(gift.getProductId());
            Integer points = product.getPoints();
            List<UserPointAccount> pointAccounts = pointAccountMapper.selectByExample(gift.getUserId());
            UserPointAccount userPointAccount = pointAccounts.get(0);
            int userP = userPointAccount.getPoints();
            int num = gift.getNum();
            Date now = new Date();
            UserOrder order = new UserOrder();
            order.setId(UUIDGenerator.generate()).setProdId(gift.getProductId())
                    .setUnitPoints(points).setNumber(num).setCreateTime(now).setMobile(gift.getMobile())
                    .setUpdateTime(now).setKinds(kinds).setDeleted(0);
            order.setOrderCodes(CommonUtils.generateOrderNo("GP")).setUserId(gift.getUserId());
            order.setTradeType(Integer.parseInt(gift.getTradeType())).setTradeState(0);
            ProductSub ps = null;
            if (kinds == 0) {
                Integer kinds2 = product.getKinds();
                if (kinds2 == 0) {
                    order.setStates(4);
                } else if(kinds2==2){
                    String subId = gift.getSubId();
                    ps = customMapper.findSubDetail(subId);
                    order.setSubsId(subId);
                    order.setKinds(1);
                    order.setStates(2);
               /* DecimalFormat df = new DecimalFormat("#");
                BigDecimal re = ps.getPrice().multiply(BigDecimal.TEN);*/
                    order.setUnitPoints(ps.getSubPoints());
                }else {
                    order.setKinds(1);
                    order.setStates(2);
                }
                //Integer oldPoints = userPointAccount.getPoints();
               /* int end = oldPoints -points;
                if(end<0){
                    return -1;
                }*/
                order.setCreateBy(gift.getUsername());
                order.setPoints( userP);
                if(kinds2 ==2){
                    order.setMoney(new BigDecimal((ps.getSubPoints()*num)-userP).divide(BigDecimal.TEN));
                }else{
                    order.setMoney(new BigDecimal((product.getPoints()*num)-userP).divide(BigDecimal.TEN));
                }
                userPointAccount.setPoints(0);
                UserAccountDetail accountDetail = new UserAccountDetail();
                accountDetail.setAccountId(userPointAccount.getId()).setCreateTime(now).setUserId(gift.getUserId())
                        .setPoints(-userP).setId(UUIDGenerator.generate()).setStates(0);
                accountDetail.setSurplusPoints(0);
                accountDetail.setOrderId(order.getId());
                accountDetail.setKinds(0).setRemark("兑换" + product.getProdName() + num + "");
                int o1 = orderMapper.insert(order);
                int o2 = pointAccountMapper.updateByPrimaryKeySelective(userPointAccount);
                int o3 = accountDetailMapper.insert(accountDetail);
                type = o1 + o2 + o3;

            } else {
                if("1".equals(gift.getFangshi())){
                    order.setExpressCompany("顺丰速运");
                }else if("2".equals(gift.getFangshi())){
                    order.setExpressCompany("闪送");
                }
                Integer kinds1 = product.getKinds();

                if(kinds1 ==1){
                    order.setStates(0).setExpressFee(150).setPoints(userP);
                }

                String addressId = gift.getAddressId();
               /* Integer oldPoints = userPointAccount.getPoints();
                int end = oldPoints - points;
                if(end<0){

                    return -1;
                }*/

                if(kinds1==2){
                    String subId = gift.getSubId();
                    ps = customMapper.findSubDetail(subId);

                    order.setStates(0).setExpressFee(150).setPoints(userP);

                    order.setSubsId(subId);
                    order.setKinds(1);
                    order.setUnitPoints(ps.getSubPoints());
                }

                userPointAccount.setPoints(0);
                order.setAddressId(addressId);
                if(kinds1 ==2){
                    if("1".equals(gift.getFangshi())){
                        order.setMoney(new BigDecimal((ps.getSubPoints()*num)+150-userP).divide(BigDecimal.TEN));
                    }else if("2".equals(gift.getFangshi())){
                        order.setMoney(new BigDecimal((ps.getSubPoints()*num)+350-userP).divide(BigDecimal.TEN));
                    }else {
                        order.setMoney(new BigDecimal((ps.getSubPoints()*num)-userP).divide(BigDecimal.TEN));
                    }

                }else{
                    if("1".equals(gift.getFangshi())){
                        order.setMoney(new BigDecimal((product.getPoints()*num)+150-userP).divide(BigDecimal.TEN));
                    }else if("2".equals(gift.getFangshi())){
                        order.setMoney(new BigDecimal((product.getPoints()*num)+350-userP).divide(BigDecimal.TEN));
                    }else {
                        order.setMoney(new BigDecimal((product.getPoints()*num)-userP).divide(BigDecimal.TEN));
                    }

                }
                UserAccountDetail accountDetail = new UserAccountDetail();
                accountDetail.setAccountId(userPointAccount.getId()).setCreateTime(now).setUserId(gift.getUserId())
                        .setPoints(-userP).setId(UUIDGenerator.generate()).setStates(0);
                accountDetail.setSurplusPoints(0);
                accountDetail.setOrderId(order.getId());
                accountDetail.setKinds(0).setRemark("兑换" + product.getProdName() + num + "");

                int m2 = orderMapper.insert(order);
                int m4 = accountDetailMapper.insert(accountDetail);
                int m3 = pointAccountMapper.updateByPrimaryKeySelective(userPointAccount);
                type = type + m2 + m3 + m4;
            }
//        type = 1;

            return type;
        }

    }

    /*
   分页获取产品数目
    */
    public List<UserOrderVO> getProductPager(String userId, int pageNum, int pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserOrderVO> pager = orderMapper.getUserOrderVOs(userId);
        List<UserOrderVO> result = pager.getResult();
        if (!result.isEmpty()) {
            DecimalFormat df = new DecimalFormat("#");
            result.forEach(or -> {
                String subId = or.getSubId();
                Integer statt = or.getTradeState();
                if(statt ==null){
                    Integer state = or.getStates();
                    if (state == 0) {
                        or.setShowStates("待寄出");
                    } else if (state == 1) {
                        or.setShowStates("已发货");
                    } else if (state == 2) {
                        or.setShowStates("到店自取");
                    } else if (state == 4) {
                        or.setShowStates("到店体验");
                    } else {
                        or.setShowStates("未知");
                    }
                } else if (statt == 0) {
                    or.setShowStates("待支付");
                } else if (statt == 1) {
                    or.setShowStates("待发货");
                } else if (statt == 2) {
                    or.setShowStates("已发货");
                } else if (statt == 3) {
                    or.setShowStates("已完成");
                } else if (statt == 4) {
                    or.setShowStates("已取消");
                }else if (statt == 5) {
                    or.setShowStates("支付失败");
                }else if (statt == 6) {
                    or.setShowStates("退款中");
                }else if (statt == 7) {
                    or.setShowStates("已退款");
                }else if (statt == 8) {
                    or.setShowStates("售后审核中");
                }else if (statt == 9) {
                    or.setShowStates("审核通过");
                }else if (statt == 10) {
                    or.setShowStates("审核未通过");
                }else if (statt == 11) {
                    or.setShowStates("待体验");
                }else if (statt == 12) {
                    or.setShowStates("待取件");
                }else {
                    Integer state = or.getStates();
                    if (state == 0) {
                        or.setShowStates("待寄出");
                    } else if (state == 1) {
                        or.setShowStates("已发货");
                    } else if (state == 2) {
                        or.setShowStates("到店自取");
                    } else if (state == 4) {
                        or.setShowStates("到店体验");
                    } else {
                        or.setShowStates("未知");
                    }
                }
                if(null!=subId){
                    ProductSub detail = customMapper.findSubDetail(subId);
                    or.setMinipic(detail.getPics());
                    or.setProductName(or.getProductName()+"("+detail.getSubname()+")");
//                    or.setPoints();
                   // BigDecimal re = detail.getPrice().multiply(BigDecimal.TEN);
                    or.setPoints(detail.getSubPoints());
                    or.setProdMoney(detail.getPrice());

                }
            });
        }
        return result;
    }


    public UserOrderDetailVO getUserOrderDetailVO(String orderId) {
        UserOrderDetailVO id = orderMapper.getOrderDetailVoById(orderId);
        String subId = id.getSubId();
        if(null!=subId){
            DecimalFormat df = new DecimalFormat("#");
            ProductSub detail = customMapper.findSubDetail(subId);
            id.setProductName(id.getProductName()+"("+detail.getSubname()+")");
            id.setMinipic(detail.getPics());
           // BigDecimal re = detail.getPrice().multiply(BigDecimal.TEN);
            id.setPoints(detail.getSubPoints());
            id.setProdMoney(detail.getPrice());
        }
        Integer states = id.getTradeState();
        if(states == null){
            Integer state = id.getStates();
            if (state == 0) {
                id.setShowStates("待寄出");
            } else if (state == 1) {
                id.setShowStates("已发货");
            } else if (state == 2) {
                id.setShowStates("到店自取");
            } else if (state == 4) {
                id.setShowStates("到店体验");
            } else {
                id.setShowStates("未知");
            }
        } else if (states == 0) {
            id.setShowStates("待支付");
        } else if (states == 1) {
            id.setShowStates("待发货");
        } else if (states == 2) {
            id.setShowStates("已发货");
        } else if (states == 3) {
            id.setShowStates("已完成");
        } else if (states == 4) {
            id.setShowStates("已取消");
        }else if (states == 5) {
            id.setShowStates("支付失败");
        }else if (states == 6) {
            id.setShowStates("退款中");
        }else if (states == 7) {
            id.setShowStates("已退款");
        }else if (states == 8) {
            id.setShowStates("售后审核中");
        }else if (states == 9) {
            id.setShowStates("审核通过");
        }else if (states == 10) {
            id.setShowStates("审核未通过");
        }else if (states == 11) {
            id.setShowStates("待体验");
        }else if (states == 12) {
            id.setShowStates("待取件");
        }else {
            Integer state = id.getStates();
            if (state == 0) {
                id.setShowStates("待寄出");
            } else if (state == 1) {
                id.setShowStates("已发货");
            } else if (state == 2) {
                id.setShowStates("到店自取");
            } else if (state == 4) {
                id.setShowStates("到店体验");
            } else {
                id.setShowStates("未知");
            }
        }
        return id;
    }

    public String getOrderId(String userId) {
        String orderId = customMapper.getOrderId(userId);
        return orderId;
    }

    public UserOrder getOrderDetail(String userId) {
        UserOrder uo = customMapper.getOrderDetail(userId);
        return uo;
    }

    public void expirePoints(String userId, String orderId) {
        Date date =new Date();
        customMapper.updateOrder(orderId,date);
        customMapper.expirePoints(userId,orderId);
        String id = UUIDGenerator.generate();

        int points = customMapper.getPoints(orderId);
        int oldPoints = customMapper.getUserPoints(userId);
        customMapper.expirePointsDetail(id,userId,orderId,date,points,oldPoints);
    }

    public UserOrder getUserOrderByCodes(String orderCode) {
        UserOrder uo = customMapper.getOrder(orderCode);
        return uo;
    }

    public void asyncHandleOrder(String id, boolean b) {
        if(b){
           Integer states =  customMapper.getOrderStates(id);
           if(states == 0){
               customMapper.updateTradeState(id,1);
           }else if(states == 2){
               customMapper.updateTradeState(id,12);
           }else if(states == 4){
               customMapper.updateTradeState(id,11);
           }

        }else{
            customMapper.updateTradeState(id,5);
        }
    }

    public UserOrder getOrderById(String orderId) {
        UserOrder uo = customMapper.getOrderById(orderId);
        return uo;
    }

    public String getUserInvite(String userId) {
        String userInvite = customMapper.getUserInvite(userId);
        return userInvite;
    }

    public void updateAccount(UserPointAccount fromUserAccount) {
        pointAccountMapper.updateByPrimaryKeySelective(fromUserAccount);
    }

    public void insertAccountDetail(UserAccountDetail fromUserAccountDetail) {
        accountDetailMapper.insert(fromUserAccountDetail);
    }

    public int findOrderPay(String userId) {
     int count =    customMapper.findOrderPay(userId);
     return count;
    }
}
